﻿using Sunny.UI;
using System.Collections.Generic;
using CoreShop.Model;
using CoreShop.Services;
using System;
using System.Windows.Forms;
using CoreShop.Library;
using SqlSugar;
using Loading;
using System.Linq;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.IO;
using System.Text;
using CoreShop.Model.FromBody;
using SqlSugar.Extensions;
using NPOI.SS.Formula.Functions;
using Newtonsoft.Json;

namespace CoreShop.App
{
    public partial class frmFoodWeighing : UIForm
    {
        private long scaleId = 0;
        List<corecmsfoodspec> foodlstSource = new List<corecmsfoodspec>();        
        OpaqueCommand cmd1 = new OpaqueCommand();        

        public frmFoodWeighing()
        {
            InitializeComponent();
            this.ShowFullScreen = AppConstVars.showFullScreen;
            this.dgvFoodList.AutoGenerateColumns = false;
        }

        private void Food_Load(object sender, System.EventArgs e)
        {
            LoadScale();
            LoadDataList(0);
        }
       
        private Expressionable<corecmsfoodspec, corecmsfood> GetExpressionable(long sScale)
        {
            var where = Expressionable.Create<corecmsfoodspec, corecmsfood>();
            where = where.And((f, s) => s.isDelete == false && s.sellStatus != 0 && f.onLine == true);
            where = where.And((f, s) => s.stand > (int)GlobalEnumVars.stand.Stand && f.weighType == (int)GlobalEnumVars.WeighType.Weigh);
            if (sScale > 0)
            {
                List<long> foodSpecIds = new corecmsscaledetailServices().AsQueryable().Where(p=>p.scaleId == sScale).Select(p=>p.foodSpecId).ToList();
                where = where.And((f, s) => foodSpecIds.Contains(f.id));
            }

            return where;
        }

        private void LoadDataList(Int64 sScale)
        {
            var count = 0;
            foodlstSource = new corecmsfoodspecServices().QueryPageSpecAsync(ref count, 1, 9999, GetExpressionable(sScale));
            var foodList = foodlstSource.OrderBy(p=>p.weighPlu).ToList();

            this.binDetail.DataSource = foodList;
            this.dgvFoodList.DataSource = this.binDetail;

            if ((sScale > 0) && (dgvFoodList.Rows.Count > 0))
               SetFoodSelected(1);
        }

        private void LoadScale()
        {
            tvFood.Nodes.Clear();
            TreeNode treeNodeTop1 = new TreeNode("所有生鲜商品");
            treeNodeTop1.Tag = 0;
            tvFood.Nodes.Add(treeNodeTop1);
            List<corecmsscale> lstSource = new corecmsscaleServices().AsQueryable().Where(p => p.id > 0).ToList();
            foreach (var item in lstSource)
            {
                TreeNode treeNode1 = new TreeNode($"{item.name}<{item.ipAddress}>");
                treeNode1.Tag = item.id.ToString();
                tvFood.Nodes.Add(treeNode1);
            }            

            tvFood.Nodes[0].Expand();
            LoadDataList(0);
        }

        private void ubtn_exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        
        private void tvFood_AfterSelect(object sender, TreeViewEventArgs e)
        {
            scaleId = CommFunc.ConvertToInt64(e.Node.Tag);
            btnDeleteData.Enabled = false;
            btnSelectGoods.Enabled = false;
            if (scaleId > 0)
            {
                btnDeleteData.Enabled = true;
                btnSelectGoods.Enabled = true;
            }
            LoadDataList(scaleId);
        }
        
        private void dgvFoodList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            int rowId = e.RowIndex;
            int colId = e.ColumnIndex;
            if ((rowId < 0) || (colId != 1)) return;
            int value = CommFunc.ConvertToInt32(dgvFoodList.Rows[rowId].Cells[1].Value) == 0 ? 1 : 0;
            dgvFoodList.Rows[rowId].Cells[1].Value = value;
        }


        private void btnSendScale_Click(object sender, EventArgs e)
        {
            List<corecmsfoodspec> detailsList = this.binDetail.DataSource as List<corecmsfoodspec>;
            var goodsList = detailsList.Where(p => p.isSelected == 1).ToList();
            if (goodsList.Count == 0)
            {
                UIMessageBox.Show("没有生鲜商品，无法下传。");
                return;
            }

            var weighPlus = goodsList.GroupBy(p => p.weighPlu).Select(g => new PluCountDto { plu = g.Key, count = g.Count()}).ToList();
            var pluRepeat = weighPlus.Where(p => p.count > 1).ToList();
            if (pluRepeat.Count > 0)
            {
                string mstr = JsonConvert.SerializeObject(pluRepeat);
                if (!ShowAskDialog($"Plu<{mstr}>有重复，是否要下传？")) return;
            }

            if (scaleId == 0)
            {
                frmScaleList frm = new frmScaleList("", true);
                if (frm.ShowDialog() == DialogResult.Yes)
                {
                    List<corecmsscale> scaleList = frm.scaleList;
                    SendToodsToScales(scaleList, goodsList);
                }
                frm.Dispose();
            }
            else
            {
                List<corecmsscale> scaleList = new corecmsscaleServices().AsQueryable().Where(p => p.id == scaleId).ToList();
                SendToodsToScales(scaleList, goodsList);
            }
        }

        private void SendToodsToScales(List<corecmsscale> scaleList, List<corecmsfoodspec> goodsList)
        {
            foreach (var item in scaleList)
            {
                switch (item.scaleType)
                {
                    case (int)GlobalEnumVars.ScaleBarcodeType.Dahua:
                        DahuiUtil.SendToScales_DH(this, item.ipAddress, item, goodsList);
                        //SendToScales_DH(item.ipAddress, item, goodsList);
                        break;//4.大华
                    case (int)GlobalEnumVars.ScaleBarcodeType.Sigang:
                        new SigangUtil().SendToScales_SG(item.ipAddress, item, goodsList);
                        break;//5.寺岗
                    case (int)GlobalEnumVars.ScaleBarcodeType.Dingjian:
                        new DingjianUtil().SendToScales_DJ(item.ipAddress, item, goodsList);
                        break;//6.顶尖
                    case (int)GlobalEnumVars.ScaleBarcodeType.Tuoliduo:
                        new TuoliduoUtil().SendToScales_TLD(item.ipAddress, item, goodsList);
                        break;//7.托利多
                }
            }
        }

        private void SetFoodSelected(int ColumnIndex)
        {
            if (dgvFoodList.Rows.Count == 0) return;
            if (dgvFoodList.Columns[ColumnIndex].Name.ToString() == "isSelected")
            {
                var value = CommFunc.ConvertToInt32(dgvFoodList.Rows[0].Cells[ColumnIndex].Value);
                value = value == 0 ? 1 : 0;
                for (int i = 0; i < dgvFoodList.Rows.Count; i++)
                {
                    dgvFoodList.Rows[i].Cells[1].Value = value;
                }
            }
        }

        private void dgvFoodList_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (dgvFoodList.Rows.Count == 0) return;
            SetFoodSelected(e.ColumnIndex);
        }

        private async void AddDataRows(List<corecmsfoodspec> foodspecList)
        {
            cmd1.ShowOpaqueLayer(pnl_Form, 125, true);
            try
            {
                List<corecmsscaledetail> details = new List<corecmsscaledetail>();                
                foreach (var foodspec in foodspecList)
                {
                    var item = new corecmsscaledetail() ;
                    item.id = $"{scaleId}_{foodspec.id}";
                    item.scaleId = scaleId;
                    item.foodSpecId = foodspec.id;
                    details.Add(item);
                }
                await new corecmsscaledetailServices().InsertOrUpdateAsync(details);
                LoadDataList(scaleId);
            }
            catch (Exception)
            {
            }
            finally { cmd1.HideOpaqueLayer(); }

        }


        private void btnSelectGoods_Click(object sender, EventArgs e)
        {
            if (scaleId == 0)
            {
                UIMessageBox.Show("没有选择电子秤，不能添加商品。");
                return;
            }
            var frm = new frmFoodSelect(null, true, (int)GlobalEnumVars.WeighType.Weigh, scaleId);
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                AddDataRows(frm.specList);
            }
            frm.Dispose();
            LoadDataList(scaleId);
        }

        private void btnScaleSet_Click(object sender, EventArgs e)
        {
            frmScaleList frm = new frmScaleList();
            frm.ShowDialog();
            frm.Dispose();
            LoadScale();
        }

        private void btnDeleteData_Click(object sender, EventArgs e)
        {
            if (scaleId == 0)
            {
                UIMessageBox.Show("没有选择电子秤，不能删除关联商品。");
                return;
            }
            if (!ShowAskDialog("提示：", "确定要删除所选的电子秤关联商品数据吗？", UIStyle.Red)) return;
            List<corecmsfoodspec> detailsList = this.binDetail.DataSource as List<corecmsfoodspec>;
            var selectIds = detailsList.Where(p => p.isSelected == 1).Select(p=>p.id).ToList();
            new corecmsscaledetailServices().Delete(p => p.scaleId == scaleId && selectIds.Contains(p.foodSpecId));
            LoadDataList(scaleId);
            ShowInfoTip("删除完成。");
        }
    }
}